'use strict';
const dayjs = require('dayjs');
const crypto = require('crypto');

const toMd5 = s => {
  return crypto.createHash('md5')
    .update(s)
    .digest('hex');
};


function encrypt(id, energy, timer, offset) {
  // 数组格式的能量值
  const energyArr = (energy + '').split('');
  // 转换所有md5中的字符
  const md5Arr = toMd5(`${id}${energy}${timer}sunok`)
    .split('')
    .map(function (t) {
      return isNaN(t) ? t.charCodeAt(0) % 10 : t;
    })
    .join('')
    .split('');

  // 插入能量数字的偏移量, 限定 1 - 9
  if (offset === undefined) {
    offset = Math.floor(Math.random() * 9) + 1;
  }
  // 能量数字的长度
  energyArr.unshift(energyArr.length);
  // 场景ID
  energyArr.unshift(id);
  for (var i = energyArr.length - 1; i >= 0; i--) {
    // 每个数字按顺序间隔5个字符在加上其实偏移量
    md5Arr[i * 5 + offset] = energyArr[i];
  }
  // 数据的起始偏移量
  md5Arr.unshift(offset);
  // 补入时间错
  md5Arr.unshift(timer);

  return md5Arr.join('');
}

const decrypt = str => {
  const strArr = Array.from(str);
  const timer = strArr.splice(0, 13)
    .join('');
  let [offset, ...otherStr] = strArr;
  let index = 0;
  offset = Number(offset);
  if (isNaN(offset)) throw new Error('二维码不正确');
  const read = () => {
    return otherStr[index++ * 5 + offset];
  };
  const sceneId = Number(read());
  const EnergyLength = Number(read());
  const Energy = Number(Array.from({ length: EnergyLength }, read)
    .join(''));
  if (isNaN(sceneId)) throw new Error('二维码不正确');
  if (isNaN(Energy)) throw new Error('二维码不正确');
  const nStr = encrypt(sceneId, Energy, timer, offset);
  if (nStr !== str) throw new Error('二维码不正确');
  return {
    sceneId,
    Energy,
    timer
  };

};
const assetWeixinResult = (data) => {
  const { errcode, errmsg } = data;
  if (errcode !== undefined && errcode !== 0) {
    throw new Error(errmsg)
  }
}
module.exports = {
  changeListTime(list, keys = [], format = 'YYYY-MM-DD HH:mm:ss') {
    if (!list) return list;
    return list.map((t) => {
      keys.forEach(key => {
        if (t[key]) {
          t[key] = dayjs(t[key])
            .format(format);
        }

      });
      return t;
    });
  },
  isEmpty(value) {
    if (value === null || value === undefined) return true;
    if (value === '') return true;
    if (value instanceof Array && value.length === 0) return true;
    if (/^\s+$|^\s?$/.test(value)) return true;
  },
  assetEmpty(value, name) {
    const err = new Error(`${name}不能为空`);
    if (module.exports.isEmpty(value)) throw err;
  },
  encrypt,
  decrypt,
  assetWeixinResult,
  toMd5
};
